<template>
	<div :style="`display: flex;flex-direction: column;height: ${state.pageHeight}px;over`">
		<uv-loading-page :loading="state.loading" loading-mode="spinner" bgColor="rgb(0,0,0,0.3)"></uv-loading-page>
		<uv-notify ref="notifyRef"></uv-notify>
		<div style="display: flex;">
			<uv-textarea v-model="state.titleValue" :maxlength="20" autoHeight count border="none"
				placeholder="给这章来个名字吧!"></uv-textarea>
			<uv-button type="primary" text="发布" @click="events.publicStore()"></uv-button>
		</div>
		<div style="flex:1;">
			<uv-textarea v-model="state.textValue" :maxlength="2000" :height="state.pageHeight - 200" count
				border="none" placeholder="尽情发挥你的想象力吧!" @focus="events.onTextareaFocus"></uv-textarea>
		</div>
	</div>
</template>

<script>
	import {
		computed,
		reactive,
		ref
	} from 'vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		addTitleApi
	} from '../../api/index.js';

	export default {
		setup() {
			const state = reactive({
				titleValue: "",
				textValue: "",
				loading: false,
				windowHeight: 0,
				keyboardHeight: 0,
				pageHeight: computed(() => state.windowHeight - state.keyboardHeight),
				parentId: ""
			});
			const notifyRef = ref(null);

			onLoad(async (e) => {
				console.log("ONLOAD", e);
				if (e.parentId) {
					state.parentId = e.parentId;


					events.onTextareaFocus();

					/**
					 * 键盘高度监听
					 */
					uni.onKeyboardHeightChange && uni.onKeyboardHeightChange(events.keyboardHeightListener)
				}

			})
			onUnload(() => {
				/**
				 * 取消键盘高度监听
				 */
				uni.offKeyboardHeightChange && uni.offKeyboardHeightChange(events.keyboardHeightListener)
			})

			const events = {
				/**
				 * 键盘监听
				 */
				keyboardHeightListener: (e) => {
					state.keyboardHeight = e.height;
				},
				/**
				 * 内容输入对焦
				 */
				onTextareaFocus: async () => {
					const {
						windowHeight
					} = await uni.getSystemInfoSync();
					state.windowHeight = windowHeight;
				},
				publicStore: async () => {
					if (!state.loading) {
						state.loading = true;

						const {
							titleValue,
							textValue,
							parentId
						} = state;

						if (titleValue == "") {
							notifyRef.value.error('给这章来个名字吧!');
							state.loading = false;
							return;
						}
						if (textValue == "") {
							notifyRef.value.error('写点什么吧!');
							state.loading = false;
							return;
						}
						const htmlStr = textValue.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(
							/\s/g, '&ensp;');


						const {
							done,
							data
						} = await addTitleApi(titleValue, htmlStr, parentId);
						if (done) {
							notifyRef.value.success('发布成功!');
							state.titleValue = "";
							state.textValue = "";
							uni.navigateBack();
						} else {
							notifyRef.value.error('发布失败!');
						}

						state.loading = false;
					}


				}
			}

			return {
				state,
				notifyRef,
				events
			}

		}
	}
</script>

<style>
</style>